package com.handsome.controller.admin;

import com.handsome.entity.AdminUser;
import com.handsome.service.*;
import lombok.SneakyThrows;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author 识时务者
 * @email 1327259918@qq.com
 */
@SuppressWarnings({"all"})
@Controller
@RequestMapping("/admin")
public class AdminController {

    @Resource
    private AdminUserService adminUserService;
    @Resource
    private BlogService blogService;
    @Resource
    private CategoryService categoryService;
    @Resource
    private LinkService linkService;
    @Resource
    private TagService tagService;
    @Resource
    private CommentService commentService;

    @Resource
    private ConfigService configService;

    @GetMapping({"/login"})
    public String login() {
        // 导致服务器异常代码
        // int a = 10 / 0;

        // 新login登录页
        return "admin/newlogin";
    }

    @GetMapping({"", "/", "/index", "/index.html"})
    public String index(HttpServletRequest request) {

        request.setAttribute("path", "index");
        request.setAttribute("categoryCount", categoryService.getTotalCategories());
        request.setAttribute("blogCount", blogService.getTotalBlogs());
        request.setAttribute("linkCount", linkService.getTotalLinks());
        request.setAttribute("tagCount", tagService.getTotalTags());
        request.setAttribute("commentCount", commentService.getTotalComments());

        return "admin/index";
    }

    // 开启异步任务
    // @Async
    // 开启定时任务
    // @Scheduled(cron = "0/4 * * * * MON-SAT")
    @SneakyThrows
    @PostMapping(value = "/login")
    public String login(@RequestParam("userName") String userName,
                        @RequestParam("password") String password,
                        @RequestParam("verifyCode") String verifyCode,
                        HttpSession session) throws InterruptedException {
        if (StringUtils.isEmpty(verifyCode)) {
            session.setAttribute("errorMsg", "验证码不能为空!");

            // 新login登录页
            return "admin/newlogin";
        }
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
            session.setAttribute("errorMsg", "用户名或密码不能为空!");

            // 新login登录页
            return "admin/newlogin";
        }
        String kaptchaCode = session.getAttribute("verifyCode") + "";
        if (StringUtils.isEmpty(kaptchaCode) || !verifyCode.equals(kaptchaCode)) {
            session.setAttribute("errorMsg", "验证码错误，老笨比了啊!");

            // 新login登录页
            return "admin/newlogin";
        }
        // 用户名和密码正确，登录成功
        AdminUser adminUser = adminUserService.login(userName, password);
        if (adminUser != null) {
            // 设置当前会话的失效时间
            // 60 * 60 * 24
            session.setMaxInactiveInterval(86400);

            Map<String, String> configs = configService.getAllConfigs();

            String yourEmail = configs.get("yourEmail");
            // 设置个人邮箱信息
            session.setAttribute("yourEmail", yourEmail);

            String yourAvatar = configs.get("yourAvatar");
            // 设置个人头像信息
            session.setAttribute("yourAvatar", yourAvatar);

            session.setAttribute("loginUser", adminUser.getNickName());
            session.setAttribute("loginUserId", adminUser.getAdminUserId());

            return "redirect:/admin/index";
        } else {
            session.setAttribute("errorMsg", "账号或密码错误!");
            // 新login登录页
            return "admin/newlogin";
        }
    }

    @GetMapping("/profile")
    public String profile(HttpServletRequest request) {

        Integer loginUserId = (int) request.getSession().getAttribute("loginUserId");

        AdminUser adminUser = adminUserService.getUserDetailById(loginUserId);
        if (adminUser == null) {
            // 新login登录页
            return "admin/newlogin";
        }
        request.setAttribute("path", "profile");
        request.setAttribute("loginUserName", adminUser.getLoginUserName());
        request.setAttribute("nickName", adminUser.getNickName());
        return "admin/profile";
    }

    @PostMapping("/profile/password")
    @ResponseBody
    public String passwordUpdate(HttpServletRequest request, @RequestParam("originalPassword") String originalPassword,
                                 @RequestParam("newPassword") String newPassword) {
        if (StringUtils.isEmpty(originalPassword) || StringUtils.isEmpty(newPassword)) {
            return "参数不能为空";
        }

        Integer loginUserId = (int) request.getSession().getAttribute("loginUserId");

        if (adminUserService.updatePassword(loginUserId, originalPassword, newPassword)) {
            //修改成功后清空session中的数据，前端控制跳转至登录页
            request.getSession().removeAttribute("loginUserId");
            request.getSession().removeAttribute("loginUser");
            request.getSession().removeAttribute("errorMsg");
            return "success";
        } else {
            return "修改失败";
        }
    }

    @PostMapping("/profile/name")
    @ResponseBody
    public String nameUpdate(HttpServletRequest request, @RequestParam("loginUserName") String loginUserName,
                             @RequestParam("nickName") String nickName) {
        if (StringUtils.isEmpty(loginUserName) || StringUtils.isEmpty(nickName)) {
            return "参数不能为空";
        }

        Integer loginUserId = (int) request.getSession().getAttribute("loginUserId");

        if (adminUserService.updateName(loginUserId, loginUserName, nickName)) {
            //修改成功后清空session中的数据，前端控制跳转至登录页
            request.getSession().removeAttribute("loginUserId");
            request.getSession().removeAttribute("loginUser");
            request.getSession().removeAttribute("errorMsg");
            return "success";
        } else {
            return "修改失败";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute("loginUserId");
        request.getSession().removeAttribute("loginUser");
        request.getSession().removeAttribute("errorMsg");

        // 新login登录页
        return "admin/newlogin";
    }
}
